import { Toast } from "vant";
import { getShopCart, addShopCart, EditShopCart } from "@/http/index.js";
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    cartData: [],
    cartItemIds:[]
  },
  mutations: {
    getStateCart(state, info) {
      let arrList = info.map((item) => {
        item.checked = true;
        return item;
      });
      state.cartData = arrList;
    },
    getCheckedIds(state) {
      let ids = []
      state.cartData
        .filter((item) => item.checked == true)
        .forEach((val) => { ids.push(val.cartItemId); });
      //console.log(ids)
      state.cartItemIds = ids;
    }
  },
  actions: {
    async getCartData({ commit }) {
      let res = await getShopCart();
      //console.log(res)
      if (res.resultCode == 200) {
        commit("getStateCart", res.data);
      }
    },
    async addCartData({ commit, dispatch }, params) {
      let resp = await addShopCart(params.id, params.count);
      //console.log(resp);
      if (resp.resultCode == 200) {
        Toast("添加购物车成功");
        dispatch("getCartData");
      }
    },
    async editCartData({ commit, dispatch }, params) {
      let resp = await EditShopCart(params.id, params.count);
      //console.log(resp);
      if (resp.resultCode == 200) {
        dispatch("getCartData");
      }
    },
  },
  getters: {
    CartNum: (state) => {
      return state.cartData.reduce((prev, next) => {
        return prev + next.goodsCount;
      }, 0);
    },
    CalSumPrice: (state) => {
      return state.cartData.reduce((prev, next) => {
        return prev + (next.checked ? next.goodsCount * next.sellingPrice : 0);
      }, 0);
    },
  },
});
export default store;
